package com.qfedu.mtl.dao.impl;

import com.qfedu.mtl.dao.UserDao;
import com.qfedu.mtl.entity.User;
import com.qfedu.mtl.util.DBUtil;
import com.qfedu.mtl.util.StrUtil;
import com.qfedu.mtl.util.handler.impl.BeanHandler;
import com.qfedu.mtl.util.handler.impl.BeanListHandler;
import com.qfedu.mtl.util.handler.impl.NumberHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @version v1.0
 * @Date 2023/9/26 21:02
 * @Author Kyi
 * @Email zywKyi@163.com
 */
public class UserDaoImpl implements UserDao {
    @Override
    public List<User> selectAll(Integer pageNum, Integer pageSize, String username) {
        List<Object> list = new ArrayList<>();
        String sql = "select * from tb_user where 1=1";
        if (!StrUtil.isNullOrEmpty(username)) {
            sql += "and username concat('%',?,'%')";
            list.add(username);
        }
        sql += " limit ?,?";
        list.add((pageNum-1)*pageSize);
        list.add(pageSize);
        List<User> userList = DBUtil.executeDQL(sql, DBUtil.getConn(), new BeanListHandler<>(User.class, true), list.toArray());
        return userList;

    }

    @Override
    public Integer selectAllTotal(String username) {
        List<Object> list = new ArrayList<>();
        String sql = "select count(*) from tb_user where 1=1 ";
        if (username != null) {
            sql += " and user_name like concat('%',?,'%')";
            list.add(username);
        }

        Long aLong = DBUtil.executeDQL(sql, DBUtil.getConn(), new NumberHandler<>(Long.class), list.toArray());
        return aLong.intValue();
    }

    @Override
    public User selectById(Integer id) {
        String sql = "select * from tb_user where user_id=?";
        User user = DBUtil.executeDQL(sql, DBUtil.getConn(), new BeanHandler<>(User.class, true), id);
            return user;
    }

    @Override
    public void update(User user) {
        String sql = "update  tb_user set user_name=?,user_password=? where user_id=? ";
        DBUtil.executeDML(sql, DBUtil.getConn(), new BeanHandler<>(User.class, true), user.getUserName(), user.getUserPassword(), user.getUserId());

    }

    @Override
    public void remove(Integer id) {
        String sql = "delete from tb_user where user_id=?";
        DBUtil.executeDML(sql, DBUtil.getConn(),  id);
    }

    @Override
    public void save(User user) {
        String sql = "insert into tb_user(user_name,user_password) values(?,?) ";
        DBUtil.executeDML(sql, DBUtil.getConn(), new BeanHandler<>(User.class, true), user.getUserName(), user.getUserPassword());


    }
}
